<?php 

/**
 * 香港SOAP提供商
 * @author liuyang
 * @since 20170804
 * @version 2.0
 */
namespace Common\Provider;   
require_once(dirname(__FILE__).'/../../../Public/wsdl/lib/nusoap.php');
class SoapProvider{  
     
    const USERNAME = "WECHAT_WSFID";
    const PASSWORD="A1709r088001"; 
    const AIRPORT_CACHE = "hk_airport_list_cache";
    const AIRLINE_CACHE = "hk_airline_list_cache";
    const HK_EXPIRE_TIME = 86400;
    const DEFAULT_AIRPORT_NAME="香港国际机场";
    const ARRIVAL=1;
    const DEPARTMENT=2;
    private static function _getPrjUrl(){
        if($_SERVER ['HTTP_HOST'] == null){
            return "file:".dirname($_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF']);
        }else{
            $url=dirname("http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF']);
            return $url;
        }
        
       
    }
    private static function send($wsdlUrl,$method,$param){
        $client = new \nusoap_client($wsdlUrl, true, '', '', '', '');  
        $client->setCredentials(self::USERNAME, self::PASSWORD);
        $client->soap_defencoding = 'UTF-8';
        $client->decode_utf8 = false;
        $client->xml_encoding = 'UTF-8'; 
         
        $result = $client->call($method,$param); 
        if(isset($result['WsfidDocument'])){
            return $result['WsfidDocument'];
        }else{
            return false;
        } 
    }
    /**
     * 航线列表
     * @param  $code
     * @return mixed
     */
    public static function getAirlineList($code){
        $newlist = S(self::AIRLINE_CACHE);
        $newlist = null;
        if($newlist == null || $newlist == false || count($newlist) < 1){
            $wsdlUrl = self::_getPrjUrl()."/Public/wsdl/GetAirlineList.wsdl";  
             
            $method = "getAirlineList";
            //$param = array("airlineCode"=>$code);
            $tmplist =  self::send($wsdlUrl, $method, array()); 
            $list = $tmplist['Airline'];
            foreach($list as $val){  
                $newlist[$val['TwoCharacterIataCode']]['IataCode'] = $val['IataCode'];
                $newlist[$val['TwoCharacterIataCode']]['Name'] = self::_getCnName($val);
            } 
            S(self::AIRLINE_CACHE,$newlist,self::HK_EXPIRE_TIME);
        }
        
        return $newlist;
    }
    /**
     * 根据航班号获取信息
     * @param unknown $airportno
     */
    public static function getFlightByAirportNo($airportNoCode,$param){
        if($airportNoCode != "" && strlen($airportNoCode)>=5){
            $airportNoCode = strtoupper($airportNoCode);
            //获取航班号前两位的航线代码
            $twoAirlineCode = substr($airportNoCode, 0,2);
            $airlineCodeList = SoapProvider::getAirlineList(); 
            $airlineCodeObj = $airlineCodeList[$twoAirlineCode];
            $param['airlineCode'] = $airlineCodeObj['IataCode'];   
            $list = SoapProvider::getFlightList($param);   
            //匹配跟航班号一样的航班
            $newlist = array();
            foreach($list as $vo){
                $tmpAirportNo = str_replace(" ","",$vo['airportno']);
                if($airportNoCode == $tmpAirportNo){
                    $newlist[] = $vo;
                }
            }
            return $newlist;
        }else{
            return array();
        }
    }
    
    private static function _getCnName($val){
        $name=$val['Name'][2]['!'];
        if($name=="." || $name =="-" || $name=="_" || $name=="," || $name=="----"){
            $name = $val['Name'][0]['!'];
        }
        return $name;
    }
    
    /**
     * 机场列表
     * @param  $code
     * @return mixed
     */
    public static function getAirportList($code){
        $newlist = S(self::AIRPORT_CACHE);  
        if($newlist == null){
            $wsdlUrl = self::_getPrjUrl()."/Public/wsdl/getAirportList.wsdl";
            
            $method = "getAirportList";
            $param = array("airportCode"=>$code);
            $list= self::send($wsdlUrl, $method, $param);  
            if($list){
                $list =  $list['Airport'];
                foreach($list as $key=>$val){
                    $tmp = array();
                    $tmp['IataCode']=$val['IataCode'];
                   // $tmp['lastname']=$val['Name'];
                   // var_dump($val['Name']);
                    $tmp['Name']=self::_getCnName($val);
                    $tmp['IcaoCode']=$val['IcaoCode'];
                    $newlist[] =$tmp;
                }
            }
            S(self::AIRPORT_CACHE,$newlist,self::HK_EXPIRE_TIME);
        }
            
        return $newlist;
    } 
    
    private static function _formatDate($dateStr){
        $list = explode("+", $dateStr);
        $date = str_replace("T", " ", $list[0]);
        return $date;
    }
    
    
    /**
     * 航班列表
     * @param unknown $param
     * @return mixed
     */
    public static function getFlightList($param){
        $wsdlUrl = self::_getPrjUrl()."/Public/wsdl/GetFlightList.wsdl";
         
        $method = "getFlightList"; 
        $tmplist =  self::send($wsdlUrl, $method, $param);
         
        $oldlist = $tmplist['WsfidFlight'];
        $list = array();
        if(isset($oldlist['GlobalObjectIdentifier'])){
            $list[]= $oldlist;
        }else{
            $list = $oldlist;
        }
        $newlist = array();
        foreach($list as $vo){
            $temp = array();
            $temp['identifier']=$vo['GlobalObjectIdentifier'];
            $temp['primary_identifier']=$vo['PrimaryObjectIdentifier'];
            $temp['airportno']=str_replace(" ", "", $vo['PrimaryIdentification']['PreferredIdentifier']); 
            $temp['airline_name']=self::_getCnName($vo['PrimaryIdentification']['Airline']);
            $temp['airline']=$vo['PrimaryIdentification']['Airline']['IataCode'];
            $type = self::ARRIVAL;
            $portCallObj=$vo['PortCall'];
            if($vo['PortCall']['Airport']==null){
                continue;
            }
            if($param['isArrival']=="T"){
                $temp['start_airport']=self::_getCnName($portCallObj['Airport']); 
                $temp['end_airport']=self::DEFAULT_AIRPORT_NAME;
            }else{
                $type = self::DEPARTMENT;
                $temp['start_airport']=self::DEFAULT_AIRPORT_NAME;
                $temp['end_airport']=self::_getCnName($portCallObj['Airport']);
            }
            $temp['plan_starttime']=strtotime(self::_formatDate( $vo['ScheduledDateTime']));
            /*
             * 1.    离港航班
                启航：使用ChocksDateTime
                其余非计划状态：使用EstimatedDateTime
                2.    抵港航班
                到闸口：使用ChocksDateTime
                着陆于：使用ActualDateTime
                其余非计划状态：使用EstimatedDateTime
             */
            $realStartTime = $vo['ChocksDateTime'];
            if($realStartTime < 1){
                $realStartTime = $vo['ActualDateTime'];
                if($realStartTime < 1){
                    $realStartTime = $vo['EstimatedDateTime'];
                }
            }
            $temp['real_starttime']=strtotime(self::_formatDate($realStartTime < 1 ? $vo['ScheduledDateTime'] : $realStartTime));//EstimatedDateTime
            $temp['plan_date']=strtotime(date("Y-m-d",strtotime($vo['ScheduledDateTime'])));
            $temp['statusinfo']=$vo['LandsideInformationDisplay']['Description'][2]['!'];
            $temp['port']=$vo['Gate'];
            $temp['baggage_number']=$vo['PrimaryBaggageReclaim']['Number'];
            $temp['desk_no']=$vo['EconomyClassDeskAssignment']['From']."-".$vo['EconomyClassDeskAssignment']['To'].",".
                             $vo['BusinessClassDeskAssignment']['From']."-".$vo['BusinessClassDeskAssignment']['To'].",".
                             $vo['FirstClassDeskAssignment']['From']."-".$vo['FirstClassDeskAssignment']['To'].",";
            $temp['terminal_port']=$vo['PrimaryBaggageReclaim']['ReclaimTerminalHalf'];
            $temp['type']=$type;
            $temp['airportcode']=$portCallObj['Airport']['IataCode'];
            $temp['createdate']=time();
            $newlist[] = $temp;
        }   
        return $newlist;
    }
    /**
     * 航班计划列表
     * @param unknown $param
     * @return mixed
     */
    public static function getFlightSchedule($param){
        $wsdlUrl = self::_getPrjUrl()."/Public/wsdl/getFlightSchedule.wsdl";
         
        $method = "getFlightSchedule";
        return self::send($wsdlUrl, $method, $param);
    }
   /**
    * 查询航班的情况
    * @param unknown $flightObj
    */
   public static function getLastestFlight($flightObj){
       //根据航班号+日期查询接口的数据
       $lastestApiObj = $flightObj;
       //$lastestApiObj['statusinfo']="延迟";
       //$lastestApiObj['real_starttime']=time()+3600*2;
       $param = array();
        
       $param['isArrival'] = $flightObj['type']== 1 ? "T" : "F";
       $param['frHour']=date("YmdHis",$flightObj['plan_starttime']);
       $param['paxCarrying']="T";
       $param['toHour']=date("Ymd",$lastestApiObj['real_starttime'])."235959";
       $airportno = str_replace(" ", "", $flightObj['airportno']);  
       $list = self::getFlightByAirportNo($airportno, $param);   
       if($list != null && count($list)>=1){
           $apiObj = $list[0]; 
           //更新本系统的数据
           $flightObj['statusinfo'] = $apiObj['statusinfo'];
           //$flightObj['statusinfo'] = "取消";

           //$flightObj['real_starttime'] = strtotime($apiObj['real_starttime'])+13800;
           $flightObj['port']=$apiObj['port'];
           //$flightObj['type']=1;
           $flightObj['baggage_number']=$apiObj['baggage_number'];
       } 
       return $flightObj;
   }
    
}

?>